package net.ankao.job.listener;

import lombok.extern.slf4j.Slf4j;
import net.ankao.job.entity.AkApplication;
import net.ankao.job.entity.AkApplicationJob;
import net.ankao.job.entity.AkJobTask;
import net.ankao.job.entity.AkNamespace;
import net.ankao.job.entity.vo.TaskMsgVO;
import net.ankao.job.listener.event.SendEmailEvent;
import net.ankao.job.service.IAkApplicationJobService;
import net.ankao.job.service.IAkApplicationService;
import net.ankao.job.service.IAkJobTaskService;
import net.ankao.job.service.IAkNamespaceService;
import net.ankao.job.utils.EmailHelper;
import net.ankao.job.utils.EmailRateLimiterUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;
import java.time.format.DateTimeFormatter;

/**
 * @author LILU
 * @date 2025-01-20 9:52
 */
@Slf4j
@Component
public class LetListener {

    @Resource
    private IAkJobTaskService taskService;

    @Resource
    private IAkApplicationJobService jobService;

    @Resource
    private IAkNamespaceService namespaceService;

    @Resource
    private IAkApplicationService applicationService;

    @Resource
    private EmailHelper emailHelper;

    @Async
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
    public void emailListener(SendEmailEvent emailEvent) {
        AkJobTask jobTask = taskService.getById(emailEvent.getTaskId());
        if (jobTask == null || jobTask.getStatus() == 1) {
            return;
        }
        AkApplicationJob applicationJob = jobService.getById(jobTask.getJobId());
        if (applicationJob == null || StringUtils.isEmpty(applicationJob.getManagerMailAddress()) || applicationJob.getMaxEmailsPerHour() == null || applicationJob.getMaxEmailsPerHour() == 0) {
            return;
        }
        // 验证是否能够发送邮件
        boolean sendEmail = EmailRateLimiterUtils.shouldSendEmail(applicationJob.getId(), applicationJob.getMaxEmailsPerHour());
        if (!sendEmail) {
            return;
        }
        AkNamespace namespace = namespaceService.getById(jobTask.getNamespaceId());
        if (namespace == null) {
            return;
        }
        AkApplication application = applicationService.getById(applicationJob.getApplicationId());
        if (application == null) {
            return;
        }
        String subject = "任务【" + applicationJob.getName() + "】执行" + (jobTask.getStatus() == -1 ? "超时" : "失败");
        TaskMsgVO taskMsgVO = TaskMsgVO.builder()
                .applicationName(application.getApplicationName())
                .dateTime(jobTask.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                .clientPath(StringUtils.isEmpty(jobTask.getClientUrl()) ? "无" : (jobTask.getClientUrl() + ":" + jobTask.getClientPort()))
                .jobName(applicationJob.getName())
                .errorMsg(jobTask.getErrorLog())
                .status(jobTask.getStatus() == -1 ? "超时" : "失败")
                .namespaceId(jobTask.getNamespaceId())
                .namespaceName(namespace.getName())
                .build();
        String text = taskMsgVO.toString();
        emailHelper.send(applicationJob.getManagerMailAddress(), subject, text);

    }


}
